from flask import Blueprint, request, jsonify
from app.services.workout_service import WorkOutService

bp = Blueprint('workout_routes', __name__)
workout_service = WorkOutService()


@bp.route('/workouts/<int:user_id>/<int:workout_id>', methods=['GET'])
def get_workout_record(user_id, workout_id):
    workout_data, status_code = workout_service.get_workout_record(user_id, workout_id)
    return jsonify(workout_data), status_code


@bp.route('/<user_id>/workouts/week', methods=['GET'])
def get_week_workout_records(user_id):
    try:
        week_workout_records , error = workout_service.get_week_records(user_id)
        if error:
            return jsonify({"message": error}), 404
        # 返回用户身体信息
        return jsonify(week_workout_records), 200

    except Exception as e:
        print(e)
        return jsonify({"error": str(e)}), 500

@bp.route('/<user_id>', methods=['GET'])
def get_today_workout(user_id):
    try:
        workout_records , error = workout_service.get_today_records(user_id)
        if error:
            return jsonify({"message": error}), 404
        # 返回用户身体信息
        return jsonify(workout_records), 200

    except Exception as e:
        print(e)
        return jsonify({"error": str(e)}), 500

@bp.route('/workouts', methods=['POST'])
def add_workout_record():
    data = request.get_json()
    workout_data, status_code = workout_service.add_workout_record(data)
    return jsonify(workout_data), status_code


@bp.route('/sport/record', methods=['POST'])
def add_sport_record():
    """处理运动记录的接口"""
    data = request.get_json()  # 获取请求体中的 JSON 数据

    # 获取数据
    user_id = data.get('userId')
    recSportItem = data.get('recSportItem')

    if not user_id or not recSportItem:
        return jsonify({"message": "缺少必要的字段"}), 400

    # 调用服务层的方法
    message, status_code = workout_service.add_sport_record(user_id, recSportItem)

    return jsonify(message), status_code


@bp.route('/workouts/update_or_create', methods=['POST'])
def update_or_create_workout_record():
    data = request.get_json()
    print(data)

    if not all(key in data for key in ['userId', 'type', 'value']):
        return jsonify({"error": "Missing required fields"}), 400

    user_id = data['userId']
    item = data['type']
    new_value = data['value']
    try:
        workout_data, status_code = workout_service.update_or_create_workout_record(user_id, item, new_value, data)
        return jsonify({
            "status": "success",
            "message": workout_data.get('message'),
            "data": workout_data.get('data')
        }), status_code
    except Exception as e:
        return jsonify({
            "status": "error",
            "message": str(e)
        }), 500


